<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
	<meta charset="utf-8">
	<title>产品列表</title>
	<meta th:replace="admin/template/head.html"/>
</head>
<body>

<div style="padding:10px 20px;">
	<form class="layui-form" action="" id="searchForm">
		<div style="display: flex;align-items: center;justify-content: flex-start;">
			<span>产品名称</span>
			<input type="text" name="title" id="title"  autocomplete="off" class="layui-input w100">
			<span>分类名称</span>
			<select name="category" id="category" lay-verify="required" >
				<option value=""></option>
				<option th:each="category:${categories}" th:value="${category.id}" th:text="${category.title}"></option>
			</select>
			<button type="button"  onclick="doSearch()" class="layui-btn layui-btn-radius" >搜索</button>
			<button type="reset" class="layui-btn  layui-btn-radius">重置</button>

		</div>
	</form>
	<div class="c-red">点击表格中的排序数字直接修改，数字大的排前面</div>
</div>


<table class="layui-hide" id="productTable" lay-filter="productTable"></table>

<script type="text/html" id="toolbarDemo">
	<div class="layui-btn-container">
		<button class="layui-btn layui-btn-sm" lay-event="add">添加</button>
		<button class="layui-btn layui-btn-sm" lay-event="refresh">刷新页面</button>
	</div>
</script>
<script type="text/html" id="barDemo">
	<a class="layui-btn layui-btn-xs" lay-event="edit">编辑</a>
	<a class="layui-btn layui-btn-xs layui-btn-warm" lay-event="sku">sku</a>
	<a class="layui-btn layui-btn-xs layui-btn-normal" lay-event="detail">详情</a>
	<a class="layui-btn layui-btn-danger layui-btn-xs" lay-event="del">删除</a>
</script>
<script type="text/html" id="picture">
	{{pictureShow(d.cover)}}
</script>
<script type="text/html" id="visibility">
	{{#  if(d.visibility==1){ }}
	<span class="c-blue">是</span>
	<a class="layui-btn layui-btn-xs layui-btn-danger" lay-event="toggleShow">设为隐藏</a>
	{{#  } else { }}
	<span class="c-999">否</span>
	<a class="layui-btn layui-btn-xs layui-btn-warm" lay-event="toggleShow">设为显示</a>
	{{#  } }}
</script>


<script th:replace="admin/template/picbox.html"></script>
<script>


	let $ ,layer,table;
	layui.use(['table','form'], function(){
		table=layui.table;
		const form = layui.form;
		$ = layui.jquery;
		layer = layui.layer;

		table.render({
			elem: '#productTable'
			,url:'/product/list'
			,toolbar: '#toolbarDemo'
			,title: '用户数据表'
			,totalRow: true
			,cols: [
				[
					// {type: 'checkbox', fixed: 'left'}
					{field:'id', title:'ID', width:80, fixed: 'left', unresize: true,}
                    ,{field:'sort', title:'排序', edit: 'text',width:80}
					,{field:'title', title:'产品名称'}
					,{field:'categoryName', title:'分类名称', width:120}
					,{field:'cover', title:'封面'}
                    ,{field:'cover', title:'预览',templet:"#picture"}
					,{field:'guidePrice', title:'零售价', width:120}
					// ,{field:'lowestPrice', title:'最低价', width:120}
					,{field:'skucount', title:'款式数量', width:120}
                    ,{field:'visibility', title:'前台显示',width:120,templet:"#visibility"}
					,{fixed: 'right', title:'操作', toolbar: '#barDemo', width:240}
				]
			]
			,page: true
			,limit:10
			,limits:[10,50,80]
            ,done:function(){
                console.log('表格渲染完成');
                lightbox();//绑定相册插件
            }
		});

		//工具栏事件
		table.on('toolbar(productTable)', function(obj){
			let checkStatus = table.checkStatus(obj.config.id);
			let data = checkStatus.data;
			switch(obj.event){
				case 'refresh':
					/* 刷新列表数据 */
					// table.reload('productTable', {page: { curr: 1}});
					window.location.reload()
					break;
				case 'getCheckLength':
					layer.msg('选中了：'+ data.length + ' 个');
					break;
				case 'isAll':
					layer.msg(checkStatus.isAll ? '全选': '未全选')
					break;
				case 'add':
					parent.layer.open({
						type: 2
						,offset:'auto'
						,title:'添加产品'
						,content:'/product/editPage'
						,area:['900px','700px']
						,btn:'关闭全部'
						,btnAlign:'c'
						,yes:function () {
							parent.layer.closeAll();
                            console.log('关闭了窗口了！！！！！！！！')
                            window.location.reload()
						}
					});
					break;
			};
		});



		//工具条事件
		table.on('tool(productTable)', function(obj){ //注：tool 是工具条事件名，test 是 table 原始容器的属性 lay-filter="对应的值"
			let id = obj.data.id; //获得当前行数据
			let layEvent = obj.event; //获得 lay-event 对应的值（也可以是表头的 event 参数对应的值）
			if(layEvent === 'del'){ //删除
				layer.confirm('真的删除行么', function(index){

					$.post('/product/delete', {id: id}, (res) => {
						layer.close(index);
						layer.msg(res.msg);
						if(res.code==0){
                            obj.del(); //删除对应行（tr）的DOM结构，并更新缓存
						}
					})

					//向服务端发送删除指令
					//todo
				});
			} else if(layEvent === 'edit') { //编辑
				parent.layer.open({
					type: 2
					,offset:'auto'
					,title:'修改产品'
					,content:'/product/editPage?id=' + id
					,area: ['80%','98%']
					,btn:'关闭全部'
					,btnAlign:'c'
				});
			} else if(layEvent === 'detail') {
				openDetail(id);
			} else if(layEvent == 'sku'){
                layer.open({
                    type:2
                    ,offset:'auto'
                    ,title:'sku编辑'
                    ,content:'/sku/listPage?pid='+id
                    ,area:['80%','98%']
                    ,btn:'关闭全部'
                    ,btnAlign:'c'
                    ,yes:function () {
                        parent.layer.closeAll();
                    }
                });
			}else if(layEvent == 'toggleShow' ){
                $.ajax({
                    type:"POST",
                    url:'/product/toggleShow',
                    // dataType:'',
                    data:{id:id},
                }).done(function(res){
                    if(res.code==0){
                        layer.msg('显示切换成功');
                        table.reload('productTable', {
                            // where: {},
                            // page: {curr:1}
                        });
                    }else{
                        layer.msg(res.msg)
                    }
                }).always(function(){

                })
            }
		});

        //监听单元格编辑
        table.on('edit(productTable)', function(obj){
            var value = obj.value.trim() //得到修改后的值
                ,data = obj.data //得到所在行所有键值
                ,field = obj.field; //得到字段

            console.log('是否NAN',isNaN(value))
            if( isNaN(value) || !value ) {
                layer.msg("非法输入")
                table.reload('productTable')
            } else {
                $.ajax({
                    type:"POST",
                    url:'/product/sort',
                    // dataType:'',
                    data:{id:data.id,sort:value},
                }).done(function(res){
                    if(res.code==0){
                        console.log('[ID: '+ data.id +'] ' + field + ' 字段更改值为：'+ value);
                        layer.msg(res.msg);
                        table.reload('productTable')
                    }else{
                        layer.msg(res.msg)
                    }
                }).always(function(){

                })
            }
        });

        //触发行双击事件,先关掉，不然越多功能越多事
        // table.on('rowDouble(product)', function(obj){
        //     let id = obj.data.id;
        //     openDetail(id);
        // });
	});


    /* 打开详情 */
    const openDetail = (id) => {
        parent.layer.open({
            type:2
            ,offset:'auto'
            ,title:'产品信息'
            ,content:'/product/detailPage?id='+id
            ,area:['1000px','700px']
            ,btn:'关闭全部'
            ,btnAlign:'c'
            ,yes:function () {
                parent.layer.closeAll();
            }
        });
    }
	function doSearch() {
		//通过jquery获取参数的值
		let title = $("#title").val();
		let categoryId = $('#category').val();
		table.reload('productTable', {
			where: {
				title: title,
				categoryId: categoryId
			},page: {
				curr:1
			}
		});

	}



</script>

</body>
</html>